<template>
  <div>

    <div>
      <div class="myItem">
        <!-- 基础信息 -->
        <div class="basic-information" >
          <div class="title-text"> 基础信息 {{result.lineName}} <a-icon @click="goToList()" :type="isHome?'home':'rollback'" title="返回" :style="{ fontSize: '20px', color: '#ccc' }" /></div>
          <div class="information-item">
            <span>所属站台：{{result.platformName}}</span>
            <span>站台类别：{{result.deviceCategory}}</span>
            <span>所属位置：{{result.deviceLocation}}</span>
            <span>设备名称：{{result.deviceCode}}</span>
            <!-- <span>设备类型：{{result.deviceType}}</span> -->
          </div>

        </div>
      </div>
      <!-- 运行报表 -->
      <!-- table区域-begin -->
      <div v-if="isPSD!='PSD'">

        <div class="table-list myItem">
          <div class="title-text">设备实时运行报表</div>
          <a-table :rowClassName='rowClassName' ref="table" size="middle" rowKey="dataTypeName" :columns="columns" :dataSource="dataSourceData" :pagination="false"  class="j-table-force-nowrap">
          </a-table>
        </div>
        <div style="height: 10px;width: 110%; background-color: #eff1f4;overflow: hidden;"></div>
        <div class="graphical-report myItem">

          <div class="condition">
            <div class="title">图形列表</div>
            <div class="query-criteria">
              <!-- <span class="dataType" v-for="i in chartDate" :key="i.value" :class="currentTab==i.value?'active':''" @click="clickQuery(i.value)">{{i.name}}</span> -->
              <a-form-model ref="advancedSearchForm">
                <a-form-model-item>
                  <!-- <a-date-picker  v-model="reviewDate" :show-time="{ format: 'HH:mm:ss' }" format="YYYY-MM-DD HH:mm:ss"  @change="onChange" /> -->
                  <a-date-picker v-model="reviewDate" style="width:100%" :disabled-date='disabledEndDate' valueFormat="YYYY-MM-DD HH:mm:00" :show-time="{ format: 'HH:mm' }" />                  
                </a-form-model-item>
              </a-form-model>
              <div style="margin-left:10px;">
                <a-button type="primary" icon="search" @click="handleSearch('',1)">查询</a-button>
                <a-button type="primary" icon="sync" ghost style="margin-left:8px;" @click="dateReset">重置</a-button>
              </div>
            </div>
          </div>
          <a-spin :spinning="lineChartLoading" tip="数据加载中">
            <line-chart :lineData="lineData" :selectedStatus='selectedStatus' @getLegendStatus='getLegendStatus' :isSmooth="typeName=='PEDC'?true:false"></line-chart>
          </a-spin>                 
          <a-button type='primary' ghost class="preBtn" @click='handlePre'>前一分钟</a-button>
          <a-button type='primary' :disabled='isDisable' ghost class="nextBtn" @click='handleNext'>后一分钟</a-button>
        </div>
      </div>

      <div class="table-list myItem" v-if="isPSD=='PSD'">
        <div class="title-text">部件列表</div>
        <a-table ref="table" size="middle"  rowKey="id" :columns="dcuColumns" :dataSource="dataSourceData" :pagination="false" class="j-table-force-nowrap">
          <template slot="action" slot-scope="text, record">
            <a @click="getDcuDetail(record)" :disabled="record.typeName=='应急门'&&record.status==0">详情</a>

            <span v-if="record.typeName=='应急门'">
              <a-divider type="vertical" />
              <!-- 0禁用 1启用 -->
              <!-- 0不反置 1反置 -->
              <a-popconfirm :title="`确定${record.status==1?'禁用':'启用'}吗?`" @confirm="() => isPartOpen(record,record.status==0?1:0)" placement="topLeft">
                <a v-if="record.status==1" :disabled="$isDisable('equipmentDetail:open')">禁用</a>
                <a v-else :disabled="$isDisable('equipmentDetail:close')">启用</a>
              </a-popconfirm>
              <a-divider type="vertical" />
              <a-popconfirm :title="`确定${record.reverse==1?'取消反置':'反置'}吗?`" @confirm="() => isPartReverse(record,record.reverse==0?1:0)" placement="topLeft">
                <a v-if="record.reverse==1" :disabled="$isDisable('equipmentDetail:noReverse')">取消反置</a>
                <a v-else :disabled="$isDisable('equipmentDetail:reverse')">反置</a>
              </a-popconfirm>                
            </span>

          </template>
        </a-table>
      </div>
    </div>

    <!-- <dcu-detail v-if="dcuDetailFlag " :equipData='equData' @closeDucDetail="dcuDetailFlag=!dcuDetailFlag"></dcu-detail> -->
  </div>
</template>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import LineChart from './modules/LineChart.vue'
import DcuDetail from './DcuDetail.vue'
import moment from 'moment';
import { getAction,postAction } from '@/api/manage'

// import { JeecgListMixin } from '@/mixins/JeecgListMixin'

export default {
  name: 'equipmentDetail',
  inject:['closeCurrent'],
  mixins: [mixinDevice],
  props: {
    equipData: {
      type: Object
    }
  },
  components: {
    LineChart,
    DcuDetail
  },
  data() {
    return {
      description: '设备详情页',
      dataSourceData: [],
      reviewDate: '',
      oprDate:'',
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      // 表头
      columns: [

        // {
        //   title: 'ID',
        //   align: "center",
        //   dataIndex: 'id'
        // },
        {
          title: '数据类型名称',
          align: "center",
          dataIndex: 'dataTypeName'
        },
        {
          title: '数据值',
          align: "center",
          dataIndex: 'dataValue'
        },
        {
          title: '单位',
          align: "center",
          dataIndex: 'unit'
        }


      ],
      // PSD表头
      dcuColumns: [

        // {
        //   title: 'ID',
        //   align: "center",
        //   dataIndex: 'id'
        // },
        {
          title: '部件编号',
          align: "center",
          dataIndex: 'deviceCode'
        },
        {
          title: '部件名称',
          align: "center",
          dataIndex: 'deviceName'
        },
        {
          title: '设备类型',
          align: "center",
          dataIndex: 'typeName'
        },
        {
          title: '健康类型',
          align: "center",
          dataIndex: 'healthyType'
        },
        {
          title: '操作',
          align: "center",
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }


      ],
      dictOptions: {},
      chartDate: [
        { name: '今日', value: '1' },
        { name: '本周', value: '2' },
        { name: '本月', value: '3' },
        { name: '全年', value: '4' },

      ],
      currentTab: 2,
      isPSD: '',
      showDetail: true,
      result:{},
      lineData:null,
      lineChartLoading:false,
      timers:null,
      equData:{},
      typeName:'',
      isDisable:false,
      selectedStatus:{},
      isHome:false,
      pId:''
    }
  },
  watch:{
    isPSD(val){
      if(val!=='PSD'){
        this.timers = setInterval(()=>{
          setTimeout(() => {
            this.getListById(this.$route.query.id)
          }, 0);
        },1000)
      }
    },
    'result.alias':{
      handler(val){
        if(val &&this.isPSD !=='PSD') {
          this.handleSearch(this.reviewDate)
        }
      }
    },
    reviewDate(val){
      if(val >=  moment().format("YYYY-MM-DD HH:mm:00")) {
        this.isDisable = true
      }else {
        this.isDisable = false
      }
    },
    oprDate(val){
      if(val ==  moment().format("YYYY-MM-DD HH:mm:00")) {
        this.isDisable = true
      }else {
        this.isDisable = false
      }
    }

  },
  created() {
    this.pId =this.$route.query.id
    console.log('pId==>>>>',this.pId) 
    this.typeName = this.$route.query.type
    this.isHome = this.$route.query.isHome
    this.getListById(this.pId)

    // this.reviewDate=[moment().subtract(1, 'minutes').format('YYYY-MM-DD HH:mm:ss') ,moment().format("YYYY-MM-DD HH:mm:ss")]
    this.reviewDate=moment().format("YYYY-MM-DD HH:mm:00")
    // this.oprDate = moment().format("YYYY-MM-DD HH:mm:00")
  },
  beforeDestroy(){
    clearInterval(this.timers)   
    this.timers = null                      
  },  
  computed: {

  },
  methods: {
    rowClassName(row,index){
      if(row.dataTypeName){
        return row.dataTypeName.includes('次数')?'rowSelect':''
      }
    },
    getListById(id){
      getAction('/basic/gdDevice/queryById',{id}).then(res=>{
        if(res&&res.code==200){
          this.result = res.result
          this.isPSD = this.result.deviceName.substring(0, 3)
          console.log('this.isPSD :>>', this.isPSD);
          if(this.isPSD !=='PSD'){
            console.log('设备实时运行报表 :>> ', res);
            this.dataSourceData = res.result.dataTypeList || [{id:1,name:'mock数据待返回'}]
          } else {
            this.getDcuList(id)
          }

        }
      })
    },
    getDcuList(id){
      getAction('/basic/gdDevice/list',{parentId:id,pageSize:20}).then(e=>{
        if(e&&e.code==200){
          console.log('PSDList',e.result.records)
          this.dataSourceData = e.result.records|| [{id:1,name:'mock数据待返回'}]

        }
      })
    },
    // 启用/禁用
    isPartOpen(params,status){
      console.log(status)
      params.status = status

      // params.deviceCategory = params.deviceCategory=="半高站台门"?"HALF_HEIGHT":"FULL_HEIGHT"
      // params.deviceLocation = this.result.deviceLocation=="下行"?"DOWN":this.result.deviceLocation=="上行"?"UP":"SYS"
      postAction('/basic/gdDevice/edit',params).then(e=>{
        if(e&&e.code==200){
          this.$message.success('操作成功')
        }
      })
    }, 
    // 反置
    isPartReverse(params,reverse){
      params.reverse = reverse
      // params.deviceCategory = params.deviceCategory=="半高站台门"?"HALF_HEIGHT":"FULL_HEIGHT"
      // params.deviceLocation = this.result.deviceLocation=="下行"?"DOWN":this.result.deviceLocation=="上行"?"UP":"SYS"      
      postAction('/basic/gdDevice/edit',params).then(e=>{
        if(e&&e.code==200){
          this.$message.success('操作成功')
        }
      }).then(()=>{
        this.getDcuList(this.pId)
      })
    },   
    goToList(){
      if(this.isHome){
        this.closeCurrent()
        this.$router.push('/statistics/dataKanban')
      }else{
        this.$router.push('/equipment/equipmentList')
      }
    },
    clickQuery(val) {
      this.currentTab = val
    },
    onChange(date, dateString) {
      console.log(dateString);
      this.reviewDate = dateString
    },
    disabledEndDate(endValue) {
      return endValue.valueOf() > moment().valueOf();
    },     
    getLegendStatus(val){
      console.log('getLegendStatus>>>>',val)
      this.selectedStatus = val
    } ,        
    handleSearch(time,flag) {

      if(this.reviewDate >=  moment().format("YYYY-MM-DD HH:mm:00")) {
        this.isDisable = true
      }else {
        this.isDisable = false
      }

      // if(flag) this.oprDate = this.reviewDate
      this.lineChartLoading = true
      // console.log('日期==》》》》',this.reviewDate)
      let params = {
        id: this.$route.query.id,
        alias:this.result.alias,
        // startTime: this.reviewDate[0],
        endTime:time || this.reviewDate
      }
      getAction('/statistics/queryChartById',params).then(res=>{
        if(res&&res.code==200){
          console.log('图表数据==》》',res.result)
          this.lineData = res.result
          this.lineChartLoading = false

        }else {
          this.$message.info(res.message)
        }
      }).finally(()=>{
          this.lineChartLoading = false
      })
    },
    dateReset(){
      this.reviewDate=moment().format("YYYY-MM-DD HH:mm:00")
      // this.oprDate=moment().format("YYYY-MM-DD HH:mm:00")
    },
    getDcuDetail(data) {
      // console.log('to=PSD部件详情》》》', data)
      this.$router.push({path:'/equipment/equipmentList/dcuDetail',query:{fName:this.result.deviceCode,type:data.deviceName,id:data.id}})
    },
    closeDetail() {
      this.showDetail = false
      this.$emit('showList')
    },
    handlePre(){
      this.reviewDate =  moment(this.reviewDate).subtract(1, 'minutes').format('YYYY-MM-DD HH:mm:00')
      console.log(this.reviewDate)
      this.handleSearch(this.reviewDate)
    },
    handleNext(){
      this.reviewDate = moment(this.reviewDate).add(1, 'minutes').format('YYYY-MM-DD HH:mm:00')
      let curTime =moment().format('YYYY-MM-DD HH:mm:00')
      if(this.reviewDate >= curTime) {
        this.reviewDate = curTime
        this.handleSearch(curTime)
        return
      }
      // this.reviewDate = endTime
      this.handleSearch(this.reviewDate)      
    },
  }
}
</script>
<style scoped lang="less">
@import '~@assets/less/common.less';

.basic-information {
  // padding-bottom:10px;
}

.title-text {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  margin-bottom: 20px;
}

.information-item {
  display: flex;
  justify-content: space-between;
}

.table-list {
  // margin-top: 10px;
}

.graphical-report {
  margin-top: 10px;
  position: relative;
  .condition {
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: space-between;
    // border: 2px solid red;
    .title {
      font-size: 16px;
      font-weight: 600;
    }
    .query-criteria {
      display: flex;
      align-items: center;
      margin-left: 100px;
      .dataType {
        display: block;
        cursor: pointer;
        height: 28px;
        line-height: 28px;
        padding: 0 7px;
        margin-right: 10px;
        &.active {
          color: #fff;
          background: #1890ff;
          border-radius: 5px;
        }
      }
      .ant-form {
        .ant-form-item {
          margin-bottom: 0;
        }
      }
    }
  }
}
.myItem {
  background: #fff;
  padding: 20px;
}
.preBtn{
  position: absolute;
  left: 20px;
  bottom:10px ;
}
.nextBtn{
  position: absolute;
  right: 20px;
  bottom:10px ;
}
.goHome{
  text-align: center;border:1px solid red;
  width:50px;height:50px;line-height:50px;border-radius:50%;
  position: fixed;
  right: 20px;  
  z-index: 99;
}
/deep/.rowSelect {
  background: #E8F6EF;
}
</style>